package com.java.compilation;

import com.java.compilation.helper.Kind;
import com.java.compilation.vm.Command;
import com.java.compilation.vm.Segment;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class VMWriter {
    private PrintWriter printWriter;

    public VMWriter(File xmlFile) {
        try {
            printWriter = new PrintWriter(xmlFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void writePush(Segment segment, int index) {
        switch (segment) {
            case CONST:
                printWriter.println("push constant " + index);
                break;
            case ARG:
                printWriter.println("push argument " + index);
                break;
            case THIS:
                printWriter.println("push this " + index);
                break;
            case LOCAL:
                printWriter.println("push local " + index);
                break;
            case STATIC:
                printWriter.println("push static " + index);
                break;
            case POINTER:
                printWriter.println("push pointer " + index);
                break;
        }
        printWriter.flush();
    }

    public void writePop(Segment segment, int index) {
        switch (segment) {
            case POINTER:
                printWriter.println("pop pointer " + index);
                break;
            case ARG:
                printWriter.println("pop argument " + index);
                break;
            case THIS:
                printWriter.println("pop this " + index);
                break;
            case LOCAL:
                printWriter.println("pop local " + index);
                break;
            case STATIC:
                printWriter.println("pop static " + index);
                break;
        }

        printWriter.flush();
    }

    public void writeArithmetic(Command command) {
        printWriter.println(command.name().toLowerCase());
        printWriter.flush();
    }

    public void writeLabel(String label) {
        printWriter.println("label " + label);
        printWriter.flush();
    }

    public void writeGoto(String label) {
        printWriter.println("goto " + label);
        printWriter.flush();
    }

    public void writeIf(String label) {
        printWriter.println("if-goto " + label);
        printWriter.flush();
    }

    public void writeCall(String name, int nArgs) {
        printWriter.println("call " + name + " " + nArgs);
        printWriter.flush();
    }

    public void writeFunction(String name, int nArgs) {
        printWriter.println("function " + name + " " + nArgs);
    }

    public void writeReturn() {
        printWriter.println("return");
        printWriter.flush();
    }

    public void close() {
        printWriter.close();
    }
}
